#!/usr/bin/env bash
# Summary: List all Go versions that contain the given executable
# Usage: goenv whence [--path] <command>

set -e
[ -n "$GOENV_DEBUG" ] && set -x

# Provide goenv completions
if [ "$1" = "--complete" ]; then
  echo --path
  exec goenv-shims --short
fi

if [ "$1" = "--path" ]; then
  print_paths="1"
  shift 1
else
  print_paths=""
fi

GOENV_COMMAND="$1"
if [ -z "$GOENV_COMMAND" ]; then
  goenv-help --usage whence >&2
  exit 1
fi

whence() {
  local command="$1"
  goenv-versions --bare | while read version; do
    path="$(goenv-prefix "$version")/bin/${command}"
    if [ ! -x "$path" ]; then
      if [ "${GOENV_DISABLE_GOPATH}" != "1" ]; then
        local gopath="${HOME}/go/${version}"
        if [ -n "${GOENV_GOPATH_PREFIX}" ]; then
          gopath="${GOENV_GOPATH_PREFIX}/${version}"
        fi
        path="${gopath}/bin/${command}"
        if [ ! -x "$path" ]; then
          continue
        fi
      else
        continue
      fi
    fi

    [ "$print_paths" ] && echo "$path" || echo "$version"
  done
}

result="$(whence "$GOENV_COMMAND")"
[ -n "$result" ] && echo "$result"
